package com.xiaolanshu.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xiaolanshu.entity.Note;
import com.xiaolanshu.exception.BusinessException;
import com.xiaolanshu.interceptor.UserHolder;
import com.xiaolanshu.service.NoteService;
import com.xiaolanshu.vo.ErrorResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

@RestController
@Slf4j
@RequestMapping("/manage")
public class NoteManagerController {

    @Autowired
    private NoteService noteService;

    /**
     * 根据用户id分页获取笔记内容
     * @return
     */
    @GetMapping
    public ResponseEntity noteManage(@RequestParam(defaultValue = "1") int page,
                                     @RequestParam(defaultValue = "10") int pageSize){
        //从线程当中获取用户id（拦截器从请求头获取了用户信息并缓存到线程当中）
        Long userId = UserHolder.getUserId();
        //根据用户id分页获取笔记内容
        Page<Note> pageInfo = noteService.notePage(page, pageSize, userId);
        return ResponseEntity.ok(pageInfo);
    }

    /**
     *
     * 删除笔记
     * @param noteId
     * @return
     */
    @PutMapping("/remove/{noteId}")
    public ResponseEntity removeNote(@PathVariable Long noteId){
        //从线程当中获取用户id（拦截器从请求头获取了用户信息并缓存到线程当中）
        Long userId = UserHolder.getUserId();
        //删除笔记
        int i = noteService.removeNote(userId, noteId);
        if(!String.valueOf(i).equals("")){
            return ResponseEntity.status(200).body("删除成功");
        }
        else {
            //抛出自定义业务异常
            throw  new BusinessException(ErrorResult.crudError());
        }
    }
}
